﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OPCAutomation;
using System.Threading;
using Chemistry.Models;

namespace Chemistry.WorkFlow
{
    /// <summary>
    /// 氧化工艺
    /// </summary>
    public class Oxidation2 : FlowBaseAll
    {
        #region 字段
        //字段
        private int _sleepfast = 500;

        private static int _relay_command;
        static bool _isgetoverstate1 = false;
        static bool _isgetoverstate2 = false;
        List<Step> _steps = new List<Step>();

        //组态数据
        static double _level_methanol_value;
        static double _flow_methanol_value;
        static double _flow_air_value;
        static double _temp_evaporator_value;
        static double _temp_oxidation_value;
        static double _gasmethanol_rate_value;
        static double _splitter_pressure_value;
        static double _watermethanol_rate_value;
        static double _evaporator_pressure_value;
        static double _temp_supheater_value;
        static double _drum_pressure_value;
        static double _level_evap_value;
        static double _methanol_concentration_value;


        //组态数据范围
        static double _level_methanol_max;
        static double _level_methanol_min;
        static double _flow_methanol_max;
        static double _flow_methanol_min;





        //增减量
        static double _level_methanol_increment;
        static double _level_methanol_decrement;
        static double _flow_methanol_increment;
        static double _flow_methanol_decrement;
        static double _flow_air_increment;
        static double _flow_air_decrement;
        static double _temp_evaporator_increment;
        static double _temp_evaporator_decrement;
        static double _temp_oxidation_increment;
        static double _temp_oxidation_decrement;
        static double _gasmethanol_rate_increment;
        static double _gasmethanol_rate_decrement;
        static double _splitter_pressure_increment;
        static double _splitter_perssure_decrement;
        static double _watermethanol_rate_increment;
        static double _watermethanol_rate_decrement;
        static double _temp_supheater_increment;
        static double _temp_supheater_decrement;
        static double _evaporator_pressure_increment;
        static double _evaporator_pressure_decrement;
        static double _drum_pressure_increment;
        static double _drum_pressure_decrement;
        static double _level_evap_increment;
        static double _level_evap_decrement;
        static double _methanol_concentration_increment;






        //命令
        private Tools.Tool.FlowCommand _flowcommand;
        string _switch1 = string.Empty;
        string _switch2 = string.Empty;
        string _prefix1 = string.Empty;
        string _prefix2 = string.Empty;
        string _llcmd = string.Empty;
        string _ywcmd = string.Empty;
        string _ylcmd = string.Empty;
        string _wdcmd = string.Empty;
        string _aicmd = string.Empty;
        string _relaycmd = string.Empty;
        int _warning1number = 0;
        int _warning2number = 0;
        int _fognumber = 0;
        int _stirnumber;

        //开关
        int open = 1; //0-48
        int close = 0; //1=49 
        #endregion

        #region 组态开关状态


        private static bool _valveMethanol_state;
        private static bool _valveFan_state;
        private static bool _valveMethanolBottom_state;
        private static bool _valveMethanolTop_state;
        private static bool _valveInSteam_state;
        private static bool _valveSteamSplitter_state;
        private static bool _valveSteamDrum_state;
        private static bool _valveInSoftwater_state;
        private static bool _valveSteamSupheater_state;
        private static bool _valveInEvaporator_state;
        private static bool _valveOutOxidation_state;
        private static bool _valveSupheaterLeft_state;
        private static bool _valveSupheaterRight_state;
        private static bool _valveMixOxidation_state;
        private static bool _valveCold_state;
        private static bool _valveInSplitter_state;
        private static bool _valveOutSteam_state;
        private static bool _valveFirefilter_state;





        #endregion

        #region OPCItem
        //阀门
        private OPCItem _valveMethanol_item;
        private OPCItem _valveFan_item;//风机
        private OPCItem _valveMethanolBottom_item;
        private OPCItem _valveMethanolTop_item;
        private OPCItem _valveInSteam_item;
        private OPCItem _valveSteamSplitter_item;//蒸汽进入蒸汽分配器阀门
        private OPCItem _valveSteamDrum_item;//蒸汽进入汽包阀门
        private OPCItem _valveInSoftwater_item;
        private OPCItem _valveSteamSupheater_item; //蒸汽进入过热器阀门
        private OPCItem _valveInEvaporator_item;//甲醇进入甲醇蒸发器阀门
        private OPCItem _valveOutOxidation_item;//氧化器自产蒸汽进蒸汽分配器阀
        private OPCItem _valveSupheaterLeft_item;
        private OPCItem _valveSupheaterRight_item;
        private OPCItem _valveMixOxidation_item;//甲醇和空气进入氧化器阀门
        private OPCItem _valveCold_item;
        private OPCItem _valveInSplitter_item;
        private OPCItem _valveOutSteam_item;
        private OPCItem _valveFirefilter_item;





        //管道
        private OPCItem _flowAir_item;
        private OPCItem _flow_InMethanol_item;
        private OPCItem _flowMethanol_item;
        private OPCItem _flowInSteam_item;
        private OPCItem _flowSplitter_item;
        private OPCItem _flowInSoftwater_item;
        private OPCItem _flowSteamSupheater_item;
        private OPCItem _flowInSplitter_item;
        private OPCItem _flowOutOxidation_item;
        private OPCItem _flowMethanolEvap_item;
        private OPCItem _flowMixSupheater_item;
        private OPCItem _flowMixOxidation_item;
        private OPCItem _flowSupheater_item;
        private OPCItem _flowFirefilter_item;
        private OPCItem _flowColdDown_item;
        private OPCItem _flowColdUp_item;
        private OPCItem _flowOutSteam_item;
        private OPCItem _flowMethanolBack_item;




        //标签
        private OPCItem _labelLevelMethanol_item;
        private OPCItem _labelFlowMethanol_item;
        private OPCItem _labelFlowAir_item;
        private OPCItem _labelTempEvaporator_item;
        private OPCItem _labelTempOxidation_item;
        private OPCItem _labelGasMethanolRate_item;
        private OPCItem _labelSplitterPressure_item;
        private OPCItem _labelWaterMethanolRate_item;
        private OPCItem _labelEvaporatorPressure_item;
        private OPCItem _labelTempSupheater_item;
        private OPCItem _labelDrumPressure_item;
        private OPCItem _labelLevelEvap_item;
        private OPCItem _labelConcentration_item;

        //闪烁
        private OPCItem _flashLevelMethanol_item;
        private OPCItem _flashFlowMethanol_item;
        private OPCItem _flashFlowAir_item;
        private OPCItem _flashTempEvaporator_item;
        private OPCItem _flashTemoOxidation_item;

        #endregion

        #region 初始化
        public Oxidation2(OPCServer opcserver, SerialPort port, bool isinner)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;

            InitFiled();
            InitOPC();
            InitOpcItem();
            InitServerData();
            InitSignal();
        }

        private void InitFiled()
        {
            _level_methanol_value = 0;
            _flow_methanol_value = 0;
            _flow_air_value = 0;
            _temp_evaporator_value = 22;
            _gasmethanol_rate_value = 0;
            _splitter_pressure_value = 0;
            _watermethanol_rate_value = 0;
            _evaporator_pressure_value = 0;
            _drum_pressure_value = 0;
            _level_evap_value = 0;
            _methanol_concentration_value = 0;

            _level_methanol_decrement = 0.2;
            _level_methanol_increment = 2;
            _flow_methanol_increment = 5;
            _flow_methanol_decrement = 5;
            _flow_air_increment = 5;
            _flow_air_increment = 5;
            _temp_evaporator_increment = 0.2;
            _temp_evaporator_decrement = 0.2;
            _temp_oxidation_increment = 0.2;
            _temp_oxidation_decrement = 0.2;
            _gasmethanol_rate_increment = 0.5;
            _gasmethanol_rate_decrement = 0.1;
            _splitter_pressure_increment = 0.1;
            _splitter_perssure_decrement = 0.1;
            _watermethanol_rate_increment = 0.2;
            _watermethanol_rate_decrement = 0.2;
            _evaporator_pressure_increment = 0.1;
            _evaporator_pressure_decrement = 0.1;
            _drum_pressure_increment = 0.02;
            _drum_pressure_decrement = 0.01;
            _level_methanol_decrement = 1;
            _level_evap_increment = 1;
            _level_evap_decrement = 0.5;
            _methanol_concentration_increment = 1;



            _flow_methanol_max = 500;
            _flow_methanol_min = 200;
            _level_methanol_max = 50;
            _level_methanol_min = 10;


        }

        private void InitOpcItem()
        {

            _valveMethanol_item = GetItem(FieldName.ValveMethanol); _valveMethanol_item.Close();
            _valveFan_item = GetItem(FieldName.ValveFan); _valveFan_item.Close();
            _valveMethanolBottom_item = GetItem(FieldName.ValveMethanolBottom); _valveMethanolBottom_item.Close();
            _valveMethanolTop_item = GetItem(FieldName.ValveMethanolTop); _valveMethanolTop_item.Close();
            _valveInSteam_item = GetItem(FieldName.ValveInSteam); _valveInSteam_item.Close();
            _valveSteamSplitter_item = GetItem(FieldName.ValveSteamSplitter); _valveSteamSplitter_item.Close();
            _valveSteamDrum_item = GetItem(FieldName.ValveSteamDrum); _valveSteamDrum_item.Close();
            _valveSteamSupheater_item = GetItem(FieldName.ValveSteamSupheater); _valveSteamSupheater_item.Close();
            _valveInSoftwater_item = GetItem(FieldName.FlowInSoftwater); _valveInSoftwater_item.Close();
            _valveInEvaporator_item = GetItem(FieldName.ValveInEvaporator); _valveInEvaporator_item.Close();
            _valveOutOxidation_item = GetItem(FieldName.ValveOutOxidation); _valveOutOxidation_item.Close();
            _valveSupheaterLeft_item = GetItem(FieldName.ValveSupheaterLeft); _valveSupheaterLeft_item.Open();
            _valveSupheaterRight_item = GetItem(FieldName.ValveSupheaterRight); _valveSupheaterRight_item.Open();
            _valveMixOxidation_item = GetItem(FieldName.ValveMixOxidation); _valveMixOxidation_item.Close();
            _valveCold_item = GetItem(FieldName.ValveCold); _valveCold_item.Close();
            _valveInSplitter_item = GetItem(FieldName.ValveInSplitter); _valveInSplitter_item.Close();
            _valveOutSteam_item = GetItem(FieldName.ValveOutSteam); _valveOutOxidation_item.Close();
            _valveFirefilter_item = GetItem(FieldName.ValveFirefilter); _valveFirefilter_item.Open();



            _flowAir_item = GetItem(FieldName.FlowAir); _flowAir_item.Close();
            _flow_InMethanol_item = GetItem(FieldName.FlowInMethanol); _flow_InMethanol_item.Close();
            _flowMethanol_item = GetItem(FieldName.FlowMethanol); _flowMethanol_item.Close();
            _flowInSteam_item = GetItem(FieldName.FlowInSteam); _flowInSoftwater_item.Close();
            _flowSplitter_item = GetItem(FieldName.FlowSplitter); _flowSplitter_item.Close();
            _flowInSoftwater_item = GetItem(FieldName.FlowInSoftwater); _flowInSoftwater_item.Close();
            _flowSteamSupheater_item = GetItem(FieldName.FlowSteamSupheater); _flowSteamSupheater_item.Close();
            _flowInSplitter_item = GetItem(FieldName.FlowInSplitter); _flowInSplitter_item.Close();
            _flowOutOxidation_item = GetItem(FieldName.FlowOutOxidation); _flowOutOxidation_item.Close();
            _flowMethanolEvap_item = GetItem(FieldName.FlowMethanolEvap); _flowMethanolEvap_item.Close();
            _flowMixSupheater_item = GetItem(FieldName.FlowMixSupheater); _flowMixSupheater_item.Open();
            _flowMixOxidation_item = GetItem(FieldName.FlowMixOxidation); _flowMixOxidation_item.Close();
            _flowSupheater_item = GetItem(FieldName.FlowSupheater); _flowSupheater_item.Close();
            _flowFirefilter_item = GetItem(FieldName.FlowFirefilter); _flowFirefilter_item.Close();
            _flowColdDown_item = GetItem(FieldName.FlowColdDown); _flowColdDown_item.Close();
            _flowColdUp_item = GetItem(FieldName.FlowColdUp); _flowColdUp_item.Close();
            _flowOutSteam_item = GetItem(FieldName.FlowOutSteam); _flowOutSteam_item.Close();
            _flowMethanol_item = GetItem(FieldName.FlowMethanolBack); _flowMethanolBack_item.Close();




            _labelLevelMethanol_item = GetItem(FieldName.LabelLevelMethanol); _labelLevelMethanol_item.Write(_level_methanol_value);
            _labelFlowMethanol_item = GetItem(FieldName.LabelFlowMethanol); _labelFlowMethanol_item.Write(_flow_methanol_value);
            _labelFlowAir_item = GetItem(FieldName.LabelFlowAir); _labelFlowAir_item.Write(_flow_air_value);
            _labelTempEvaporator_item = GetItem(FieldName.LabelTempEvaporator); _labelTempEvaporator_item.Write(_temp_evaporator_value);
            _labelTempOxidation_item = GetItem(FieldName.LabelTempOxidation); _labelTempOxidation_item.Write(_temp_oxidation_value);
            _labelGasMethanolRate_item = GetItem(FieldName.LabelGasMethanolRate); _labelGasMethanolRate_item.Write(_gasmethanol_rate_value);
            _labelSplitterPressure_item = GetItem(FieldName.LabelSplitterPressure); _labelSplitterPressure_item.Write(_splitter_pressure_value);
            _labelWaterMethanolRate_item = GetItem(FieldName.LabelWaterMethanolRate); _labelWaterMethanolRate_item.Write(_watermethanol_rate_value);
            _labelEvaporatorPressure_item = GetItem(FieldName.LabelEvaporatorPressure); _labelEvaporatorPressure_item.Write(_evaporator_pressure_value);
            _labelTempSupheater_item = GetItem(FieldName.LabelTempSupheater); _labelTempSupheater_item.Write(_temp_supheater_value);
            _labelDrumPressure_item = GetItem(FieldName.LabelDrumPressure); _labelDrumPressure_item.Write(_drum_pressure_value);
            _labelLevelEvap_item = GetItem(FieldName.LabelLevelEvap); _labelLevelEvap_item.Write(_level_evap_value);
            _labelConcentration_item = GetItem(FieldName.LabelConcentration); _labelConcentration_item.Write(_methanol_concentration_value);




            _flashLevelMethanol_item = GetItem(FieldName.FlashLevelMethanol); _flashLevelMethanol_item.Close();
            _flashFlowMethanol_item = GetItem(FieldName.FlashFlowMethanol); _flashFlowMethanol_item.Close();
            _flashFlowAir_item = GetItem(FieldName.FlashFlowAir); _flashFlowAir_item.Close();
            _flashTempEvaporator_item = GetItem(FieldName.FlashTempEvaporator); _flashTempEvaporator_item.Close();
            _flashTemoOxidation_item = GetItem(FieldName.FlashTemoOxidation); _flashTemoOxidation_item.Close();


        }

        private async void InitServerData()
        {
            _details = await GetDetails(this.GetType().Name);
            _abnormals = await GetAbnormals(this.GetType().Name);
        }

        private void InitSignal()
        {
            if (Isinner)
            {
                ListenSignal();
                open = 1;
                close = 0;
            }
            else
            {
                InitFlowCommandData();
                _serialPort.DataReceived += _serialPort_DataReceived;
                InitOpcItemWithSerialPort();
                ListenSerialPortAndAbnormalData();
                open = 48;
                close = 49;
            }
        }

        #region InitSignal
        private void ListenSignal()
        {
            Task t = new Task(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    int valveMethanol = Convert.ToInt32(ReadItem(FieldName.ValveMethanol));
                    int valveMethanolBottom = Convert.ToInt32(ReadItem(FieldName.ValveMethanolBottom));
                    int valveMethanoltop = Convert.ToInt32(ReadItem(FieldName.ValveMethanolTop));
                    int valveFan = Convert.ToInt32(ReadItem(FieldName.ValveFan));
                    int valveInSteam = Convert.ToInt32(ReadItem(FieldName.ValveInSteam));
                    int valveSteamSplitter = Convert.ToInt32(ReadItem(FieldName.ValveSteamSplitter));
                    int valveSteamDrum = Convert.ToInt32(ReadItem(FieldName.ValveSteamDrum));
                    int valveInSoftwater = Convert.ToInt32(ReadItem(FieldName.ValveInSoftwater));
                    int valveSteamSupheater = Convert.ToInt32(ReadItem(FieldName.ValveSteamSupheater));
                    int valveInEvaporator = Convert.ToInt32(ReadItem(FieldName.ValveInEvaporator));
                    int valveOutOxidation = Convert.ToInt32(ReadItem(FieldName.ValveOutOxidation));
                    //int valveSupheaterLeft = Convert.ToInt32(ReadItem(FieldName.ValveSupheaterLeft));
                    //int valveSupheaterRight = Convert.ToInt32(ReadItem(FieldName.ValveSupheaterRight));
                    int valveMixOxidation = Convert.ToInt32(ReadItem(FieldName.ValveMixOxidation));
                    int valveInSplitter = Convert.ToInt32(ReadItem(FieldName.ValveInSplitter));
                    int valveOutSteam = Convert.ToInt32(ReadItem(FieldName.ValveOutSteam));
                    //int valveFirefilter = Convert.ToInt32(ReadItem(FieldName.ValveFirefilter));
                    int valveCold = Convert.ToInt32(ReadItem(FieldName.ValveCold));

                    _valveMethanol_state = valveMethanol == open;
                    _valveFan_state = valveFan == open;
                    _valveMethanolBottom_state = valveMethanolBottom == open;
                    _valveMethanolTop_state = valveMethanoltop == open;
                    _valveInSteam_state = valveInSteam == open;
                    _valveSteamSplitter_state = valveSteamSplitter == open;
                    _valveSteamDrum_state = valveSteamDrum == open;
                    _valveInSoftwater_state = valveInSoftwater == open;
                    _valveSteamSupheater_state = valveSteamSupheater == open;
                    _valveInEvaporator_state = valveInEvaporator == open;
                    _valveOutOxidation_state = valveOutOxidation == open;
                    //_valveSupheaterLeft_state = valveSupheaterLeft == open;
                    //_valveSupheaterRight_state = valveSupheaterRight == open;
                    _valveMixOxidation_state = valveMixOxidation == open;
                    _valveInSplitter_state = valveInSplitter == open;
                    _valveOutSteam_state = valveOutSteam == open;
                    //_valveFirefilter_state = valveFirefilter == open;
                    _valveCold_state = valveCold == open;

                    DateTime now = DateTime.Now;
                    Step step = new Step()
                    {

                        status = new Dictionary<StatusName, double>()
                        {   
                            {StatusName.甲醇进料阀,valveMethanol},
                            {StatusName.甲醇流量计下阀,valveMethanolBottom},
                            {StatusName.甲醇流量计上阀,valveMethanoltop},
                            {StatusName.风机阀,valveFan},
                            {StatusName.蒸汽进蒸汽分配器阀, valveSteamSplitter},
                            {StatusName.蒸汽进汽包阀,valveSteamDrum},
                            {StatusName.软水进阀,valveInSoftwater},
                            //{StatusName.蒸汽进过热器及阻火过滤器阀,valveFirefilter},
                            {StatusName.甲醇进甲醇蒸发器阀,valveInEvaporator},
                            {StatusName.氧化器蒸汽进蒸汽分配器阀门,valveOutOxidation},
                            //{StatusName.过热器左侧阀,valveSupheaterLeft},
                            //{StatusName.过热器右侧阀,valveSupheaterRight},
                            {StatusName.混合气体进氧化器阀,valveMixOxidation},                           
                            {StatusName.甲醇液位,_level_methanol_value},
                            {StatusName.甲醇流量,_flow_methanol_value},
                            {StatusName.空气流量,_flow_air_value},
                            {StatusName.甲醇蒸发器温度,_temp_evaporator_value},
                            {StatusName.氧化器温度,_temp_oxidation_value},
                            {StatusName.氧醇比,_gasmethanol_rate_value},
                            {StatusName.水醇比,_watermethanol_rate_value},
                            {StatusName.蒸汽分配器压力,_splitter_pressure_value},
                            {StatusName.汽包蒸汽流入蒸汽分配器阀,valveInSplitter},
                            {StatusName.蒸发器液位,_level_evap_value},
                            {StatusName.甲醇平衡浓度,_methanol_concentration_value},
                            {StatusName.循环水进氧化器阀,valveCold},
                            
                        },
                        Date = now

                    };
                    _steps.Add(step);
                    Thread.Sleep(_sleepfast);


                }
            });
            t.Start();
        }

        private void InitFlowCommandData()
        {
            _flowcommand = Tools.Tool.GetFlowCommand(this.GetType().Name);
            _switch1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "switch1").Value;
            _switch2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "switch2").Value;
            _prefix1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix1").Value;
            _prefix2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix2").Value;
            _llcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "llcmd").Value;
            _ywcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ywcmd").Value;
            _ylcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ylcmd").Value;
            _wdcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "wdcmd").Value;
            _aicmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "aicmd").Value;
            _relaycmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "relaycmd").Value;
            _warning1number = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning1").Value);
            _warning2number = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning2").Value);
            _fognumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "fog").Value);
            _stirnumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "stir").Value);
        }

        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

        }

        private void InitOpcItemWithSerialPort()
        {

        }

        private void ListenSerialPortAndAbnormalData()
        {

        }
        #endregion

        #endregion

        #region 重写公共方法
        public override void Begin()
        {
            ListenOPCRelation();
        }
        public override async Task<string> CheckDefault()
        {
            return string.Empty;
        }
        public override void Over()
        {
            this._listenCts.Cancel();
            CalcFlowAndStep();
            Score = CalcScore();
            Finish();

        }


        private void ListenOPCRelation()
        {
            ThreadPool.QueueUserWorkItem(o =>
            {
                #region 注释部分
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {

                    }

                });
                #endregion

                #region 风机
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveFan_state)
                        {
                            if (!Isinner) _valveFan_item.Open();
                            _flowAir_item.StartFlow();
                            _flow_air_increment = _flow_air_value < 800 ? 5 : 1;
                            _flow_air_increment = _flow_air_value > 1200 ? 0 : 1;

                            _flow_air_value += _flow_air_increment;
                            _labelFlowAir_item.Write(_flow_air_value);
                        }
                        else
                        {
                            if (!Isinner) _valveFan_item.Close();
                            _flowAir_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }

                });
                #endregion

                #region 甲醇进料
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveMethanol_state)
                        {
                            if (!Isinner)
                                _valveMethanol_item.Open();
                            _flow_InMethanol_item.StartFlow();
                            _flowMethanolBack_item.StartFlow();

                            _level_methanol_value += _level_methanol_increment;
                            //防止甲醇满料时，将出现预警
                            if (_level_methanol_value > 55)
                            {
                                _level_methanol_value = _level_methanol_max;
                            }
                            if (_level_methanol_value <= _level_methanol_max)
                            {
                                _labelLevelMethanol_item.Write(_level_methanol_value);
                            }
                        }
                        else
                        {
                            if (!Isinner)
                                _valveMethanol_item.Close();
                            _flow_InMethanol_item.StopFlow();
                            _flowMethanolBack_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 甲醇
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {

                        if (_valveMethanolTop_state)
                        {
                            if (!Isinner)
                                _valveMethanolTop_item.Open();
                        }
                        else
                        {
                            if (!Isinner)
                                _valveMethanolTop_item.Close();
                        }

                        if (_valveMethanolBottom_state)
                        {
                            if (!Isinner)
                                _valveMethanolBottom_item.Open();
                        }
                        else
                        {
                            if (!Isinner)
                                _valveMethanolBottom_item.Close();
                        }

                        if (_valveMethanolTop_state && _valveMethanolBottom_state)
                        {
                            _flowMethanol_item.Open();
                            _flow_methanol_increment = _flow_methanol_value < _flow_methanol_min ? 5 : 1;
                            if (_flow_methanol_value > _flow_methanol_max)
                            {
                                _flow_methanol_value = _flow_methanol_max;
                            }
                            _flow_methanol_value += _flow_methanol_increment;
                            _labelFlowMethanol_item.Write(_flow_methanol_value);

                            _level_methanol_decrement = _level_methanol_value < 10 ? 0 : 2;
                            _level_methanol_value -= _level_methanol_decrement;
                            if (_level_methanol_value > 0)
                            {
                                _labelLevelMethanol_item.Write(_level_methanol_value);

                            }


                        }
                        else
                        {
                            _flowMethanol_item.Close();
                        }

                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 甲醇 空气二元混合气体进入甲醇蒸发器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {

                        if (_valveInEvaporator_state)
                        {
                            if (!Isinner)
                                _valveInEvaporator_item.Open();
                            _flowMethanolEvap_item.StartFlow();
                            //混合气体进入时，甲醇蒸发器内温度升高                            
                            //[47-50]   [40-55]
                            _temp_evaporator_increment = _temp_evaporator_value < 40 ? 0.5 : 0.3;
                            _temp_evaporator_increment = _temp_evaporator_value > 55 ? 0 : 0.3;
                            _temp_evaporator_value += _temp_evaporator_increment;
                            _labelTempEvaporator_item.Write(_temp_evaporator_value);
                            //甲醇平衡浓度
                            _methanol_concentration_value += _methanol_concentration_increment;
                            _methanol_concentration_increment = _methanol_concentration_value >= 85 ? 0 : 1;
                            _labelConcentration_item.Write(_methanol_concentration_value);

                            //if(_temp_evaporator_value<44)
                            //{
                            //     //甲醇进入甲醇液位槽，液位上升???
                            //     _level_evap_value +=_level_evap_increment;
                            //     _labelLevelEvap_item.Write(_level_evap_value);
                            //}
                            ////压力
                            //_evaporator_pressure_increment = _evaporator_pressure_value < 6 ? 1 : 0.5;
                            //_evaporator_pressure_increment = _evaporator_pressure_value > 50 ? 0 : 0.5;
                            //_evaporator_pressure_value += _evaporator_pressure_increment;
                            //_labelEvaporatorPressure_item.Write(_evaporator_pressure_value);

                            //蒸发器液位在40%-70%,甲醇蒸发时，液位降低
                            //if (_temp_evaporator_value > 44)
                            //{
                            //    _level_evap_decrement = _level_evap_value < 70 ? 0.5 : 1;
                            //    _level_evap_decrement = _level_evap_value < 40 ? 0 : 0.5;
                            //    _level_evap_value -= _level_evap_decrement;
                            //    _labelLevelEvap_item.Write(_level_evap_value);
                            //}


                            //甲醇 空气经甲醇蒸发器进入过热器，过热器温度上升
                            _temp_supheater_increment = _temp_supheater_increment < 110 ? 1 : 0.5;
                            _temp_supheater_increment = _temp_supheater_value > 111 ? 0 : 0.5;
                            _temp_supheater_value += _temp_supheater_increment;
                            _labelTempSupheater_item.Write(_temp_supheater_value);


                        }
                        else
                        {
                            if (!Isinner)
                                _valveInEvaporator_item.Close();
                            _flowMethanolEvap_item.StopFlow();

                        }
                        Thread.Sleep(_sleepfast);
                    }

                });
                #endregion

                #region 甲醇 空气二元混合气体进入氧化器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveMixOxidation_state)
                        {
                            if (!Isinner)
                                _valveMixOxidation_item.Open();
                            _flowMethanol_item.StartFlow();
                            //氧化器温度上升
                            _temp_oxidation_increment = _temp_oxidation_value < 80 ? 1.5 : 1;
                            _temp_oxidation_value += _temp_supheater_increment;
                            _labelTempOxidation_item.Write(_temp_oxidation_value);
                        }
                        else
                        {
                            if (!Isinner)
                                _valveMixOxidation_item.Close();
                            _flowMixOxidation_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 蒸汽

                #region 来自外界蒸汽
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInSteam_state)
                        {
                            if (!Isinner)
                                _valveInSteam_item.Open();
                            _flowInSteam_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                _valveInSteam_item.Close();
                            _flowInSteam_item.StopFlow();
                        }

                    }
                    Thread.Sleep(_sleepfast);

                });
                #endregion

                #region 蒸汽流入蒸汽分配器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveSteamSplitter_state)
                        {
                            if (!Isinner)
                                _valveSteamSplitter_item.Open();
                            _flowInSplitter_item.StartFlow();
                            //[0.4-0.6]  [0.3-0.6]
                            _splitter_pressure_increment = _splitter_pressure_value < 0.25 ? 0.02 : 0.01;
                            _splitter_pressure_increment = _splitter_pressure_value > 0.32 ? 0 : 0.01;
                            _splitter_pressure_value += _splitter_pressure_increment;
                            _labelSplitterPressure_item.Write(_splitter_pressure_value);
                        }
                        else
                        {
                            if (!Isinner)
                                _valveSteamSplitter_item.Close();
                            _flowInSplitter_item.StartFlow();
                        }
                        Thread.Sleep(_sleepfast);

                    }

                });

                #endregion

                #region 蒸汽分配器用气处
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutSteam_state)
                        {
                            if (!Isinner)
                                _valveOutSteam_item.Open();
                            _flowOutSteam_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                _valveOutSteam_item.Close();
                            _flowOutSteam_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region  配料蒸汽进  过热器 阻火过滤器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveSteamSupheater_state)
                        {
                            if (!Isinner)
                                _valveSteamSupheater_item.Open();
                            //_flowMixSupheater_item.StartFlow();
                            _flowSteamSupheater_item.StartFlow();
                            _flowSupheater_item.StartFlow();
                            _flowFirefilter_item.StartFlow();

                            //蒸汽进入过热器温度升高到110左右
                            _temp_supheater_increment = _temp_supheater_increment < 110 ? 1 : 0.3;
                            _temp_supheater_increment = _temp_supheater_value > 111 ? 0 : 0.3;
                            _temp_supheater_value += _temp_supheater_increment;
                            _labelTempSupheater_item.Write(_temp_supheater_value);

                        }
                        else
                        {
                            if (!Isinner)
                                _valveSteamSupheater_item.Close();
                            //_flowMixSupheater_item.StopFlow();
                            _flowSteamSupheater_item.StopFlow();
                            _flowFirefilter_item.StartFlow();
                            _flowFirefilter_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);

                    }

                });
                #endregion

                #region 蒸汽进入过热器
                //Task.Run(() =>
                //    {
                //        while(!_listenCts.IsCancellationRequested)
                //        {
                //            if(_valveSupheaterLeft_state&&_valveSupheaterLeft_state)
                //            {
                //                if(!Isinner)
                //                {
                //                    _valveSupheaterLeft_item.Open();
                //                    _valveSupheaterRight_item.Open();
                //                }
                //                _flowSupheater_item.StartFlow();
                //            }
                //            else
                //            {
                //                if(!Isinner)
                //                {
                //                    _valveSupheaterLeft_item.Close();
                //                    _valveSupheaterRight_item.Close();
                //                }
                //                C
                //            }
                //            Thread.Sleep(_sleepfast);
                //        }
                //    });
                #endregion

                #region 蒸汽进入阻火过滤器
                //Task.Run(() =>
                //    {
                //        while(!_listenCts.IsCancellationRequested)
                //        {
                //            if (_valveFirefilter_state)
                //            {
                //                if (!Isinner)
                //                    _valveFirefilter_item.Open();
                //                _flowFirefilter_item.StartFlow();
                //            }
                //            else
                //            {
                //                if (!Isinner)
                //                    _valveFirefilter_item.Close();
                //                _flowFirefilter_item.StopFlow();

                //            }
                //            Thread.Sleep(_sleepfast);

                //        }
                //    });
                #endregion


                #endregion

                #region  蒸汽进入氧化器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveSteamSupheater_state && _valveMixOxidation_state)
                        {
                            if (!Isinner)
                                _valveMixOxidation_item.Open();
                            _flowMixOxidation_item.StartFlow();
                            //[630-660]  [620-660]
                            _temp_oxidation_increment = _temp_oxidation_value < 620 ? 10 : 5;
                            _temp_oxidation_increment = _temp_oxidation_value > 660 ? 0 : 5;
                            _temp_oxidation_value += _temp_oxidation_increment;
                            _labelTempOxidation_item.Write(_temp_oxidation_value);
                        }
                        else
                        {
                            if (!Isinner)
                                _valveMixOxidation_item.Close();
                            _flowMixOxidation_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 计算氧醇 水醇比例

                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        _gasmethanol_rate_increment = _gasmethanol_rate_value < 0.26 ? 0.05 : 0.01;
                        _gasmethanol_rate_increment = _gasmethanol_rate_value > 0.48 ? 0 : 0.01;
                        if (_valveFan_state && _valveInEvaporator_state && _valveMixOxidation_state)
                        {
                            _gasmethanol_rate_value += _gasmethanol_rate_increment;
                            _labelGasMethanolRate_item.Write(_gasmethanol_rate_value);
                        }


                        _watermethanol_rate_increment = _watermethanol_rate_value < 54 ? 1 : 0.5;
                        _watermethanol_rate_increment = _watermethanol_rate_value > 64 ? 0 : 0.5;
                        if (_valveOutSteam_state && _valveSteamSupheater_state && _valveMixOxidation_state)
                        {
                            _watermethanol_rate_value += _watermethanol_rate_increment;
                            _labelWaterMethanolRate_item.Write(_watermethanol_rate_value);
                        }


                        Thread.Sleep(_sleepfast);
                    }

                });
                #endregion

                #region 氧化器反应产生蒸汽流入 蒸汽分配器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveOutOxidation_state)
                        {
                            if (!Isinner)
                                _valveOutOxidation_item.Open();
                            _flowOutOxidation_item.StartFlow();

                            //蒸汽分配器气压变化
                            _splitter_pressure_increment = _splitter_pressure_value < 0.25 ? 0.02 : 0.01;
                            _splitter_pressure_increment = _splitter_pressure_value > 0.25 ? 0 : 0.01;
                            _splitter_pressure_value += _splitter_pressure_increment;
                            _labelSplitterPressure_item.Write(_splitter_pressure_value);
                        }
                        else
                        {
                            if (!Isinner)
                                _valveOutOxidation_item.Close();
                            _flowOutOxidation_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);

                    }
                });
                #endregion

                #region 软水流入汽包
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInSoftwater_state)
                        {
                            if (!Isinner)
                                _valveInSoftwater_item.Open();
                            _flowInSoftwater_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                            {
                                _valveInSoftwater_item.Close();
                                _flowInSoftwater_item.StopFlow();
                            }
                        }

                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region  反应正常时 循环水进入氧化器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveCold_state)
                        {
                            if (!Isinner)
                                _valveCold_item.Open();
                            _flowColdUp_item.StartFlow();
                            _flowColdDown_item.StartFlow();
                            //汽包压力上升
                            _drum_pressure_increment = _drum_pressure_value < 0.25 ? 0.02 : 0.01;

                            _drum_pressure_value += _drum_pressure_increment;
                            _labelDrumPressure_item.Write(_drum_pressure_value);

                            //氧化器内温度下降
                            _temp_evaporator_decrement = _temp_evaporator_value > 400 ? 2 : 1;
                            _temp_evaporator_decrement = _temp_evaporator_value > 200 ? 1 : 0.5;
                            _temp_evaporator_value -= _temp_evaporator_decrement;
                            _labelTempEvaporator_item.Write(_temp_evaporator_value);

                        }
                        else
                        {
                            if (!Isinner)
                            {
                                _valveCold_item.Close();
                                _flowColdUp_item.StopFlow();
                                _flowColdDown_item.StopFlow();
                            }
                        }
                        Thread.Sleep(_sleepfast);

                    }
                });

                #endregion

                #region 汽包中蒸汽流入蒸汽分配器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveSteamDrum_state)
                        {
                            if (!Isinner)
                                _valveSteamDrum_item.Open();
                            _flowSplitter_item.StartFlow();
                            //汽包中压力下降

                            _drum_pressure_decrement = _drum_pressure_value < 0.32 ? 0.01 : 0.02;
                            _drum_pressure_decrement = _drum_pressure_value < 0.25 ? 0 : 0.01;
                            _drum_pressure_value -= _drum_pressure_decrement;
                            _labelDrumPressure_item.Write(_drum_pressure_value);
                            //蒸汽分配器中压力升高
                            _splitter_pressure_increment = _splitter_pressure_value < 0.25 ? 0.01 : 0;
                            _splitter_pressure_value += _splitter_pressure_increment;
                            _labelSplitterPressure_item.Write(_splitter_pressure_value);

                        }
                        else
                        {
                            if (!Isinner)
                                _valveSteamDrum_item.Close();
                            _flowSplitter_item.StopFlow();
                        }
                    }
                    Thread.Sleep(_sleepfast);
                });
                #endregion


            });
        }

        private void CalcFlowAndStep()
        {
            //流程步骤
            //1正常开车
            //1.1 甲醇液位
            var methanol_open_item = _steps.Where(i => i.status[StatusName.甲醇进料阀] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            var methanol_close_item = _steps.Where(i => i.status[StatusName.甲醇进料阀] == close && i.Date > methanol_open_item.Date).FirstOrDefault();
            //1.2 甲醇流量
            var avg_methanol_count = _steps.Count(i => i.status[StatusName.甲醇流量计下阀] == open && i.status[StatusName.甲醇流量计上阀] == open);
            var avg_methanol = avg_methanol_count > 0 ? _steps.Where(i => i.status[StatusName.甲醇流量计下阀] == open &&
                i.status[StatusName.甲醇流量计上阀] == open).Average(i => i.status[StatusName.甲醇流量]) : -1;
            //1.3 甲醇平衡浓度
            var methanol_concertration_item = _steps.Where(i => i.status[StatusName.甲醇进甲醇蒸发器阀] == open).OrderByDescending(i => i.status[StatusName.甲醇平衡浓度])
                .ThenByDescending(i => i.Date).FirstOrDefault();
            //1.4 空气流量
            var avg_flowair_count = _steps.Count(i => i.status[StatusName.风机阀] == open);
            var avg_flowair = avg_flowair_count > 0 ? _steps.Where(i => i.status[StatusName.风机阀] == open)
                .Average(i => i.status[StatusName.空气流量]) : -1;
            //1.5 蒸发器温度
            var avg_tempevaporator_count = _steps.Count(i => i.status[StatusName.甲醇进甲醇蒸发器阀] == open);
            var avg_tempevaporator = avg_tempevaporator_count > 0 ? _steps.Where(i => i.status[StatusName.甲醇进甲醇蒸发器阀] == open)
                .Average(i => i.status[StatusName.甲醇蒸发器温度]) : -1;
            //1.6 过热器温度
            var avg_tempsupheater_count = _steps.Where(i => i.status[StatusName.甲醇进甲醇蒸发器阀] == open);
            var avg_tempsupheater = avg_tempevaporator_count > 0 ? _steps.Where(i => i.status[StatusName.甲醇进甲醇蒸发器阀] == open)
                .Average(i => i.status[StatusName.过热器温度]) : -1;
            //1.7 氧化器温度
            var tempoxidation_item = _steps.Where(i => i.status[StatusName.混合气体进氧化器阀] == open).OrderByDescending(i => i.Date)
                .FirstOrDefault();
            var avg_tempoxidation_count = _steps.Count(i => i.status[StatusName.混合气体进氧化器阀] == open);
            var avg_tempoxidation = avg_tempevaporator_count > 0 ? _steps.Where(i => i.status[StatusName.混合气体进氧化器阀] == open)
                .Average(i => i.status[StatusName.氧化器温度]) : -1;
            //1.8 水醇比
            var watermethanol_rate_count = _steps.Count(i => i.status[StatusName.软水进阀] == open
                && i.status[StatusName.循环水进氧化器阀] == open && i.status[StatusName.混合气体进氧化器阀] == open);
            var watermethanol_rate = watermethanol_rate_count > 0 ? _steps.Where(i => i.status[StatusName.软水进阀] == open &&
                i.status[StatusName.循环水进氧化器阀] == open && i.status[StatusName.混合气体进氧化器阀] == open).Average(
                i => i.status[StatusName.水醇比]) : -1;
            //1.9 甲醇比
            var gasmethanol_rate_count = _steps.Count(i => i.status[StatusName.风机阀] == open &&
                i.status[StatusName.甲醇进甲醇蒸发器阀] == open && i.status[StatusName.混合气体进氧化器阀] == open);
            var gasmethanol_rate = gasmethanol_rate_count > 0 ? _steps.Where(i => i.status[StatusName.甲醇进甲醇蒸发器阀] == open &&
                i.status[StatusName.风机阀] == open && i.status[StatusName.混合气体进氧化器阀] == open)
                .Average(i => i.status[StatusName.氧醇比]) : -1;
            //1.10 蒸汽分配器压力(最后平衡压力)
            var splitterpressure_item = _steps.Where(i => i.status[StatusName.汽包蒸汽流入蒸汽分配器阀] == open).
                OrderByDescending(i => i.status[StatusName.蒸汽分配器压力]).ThenByDescending(i => i.Date).FirstOrDefault();


            //1.11 气泡压力（平衡压力）















        }

        #endregion


        #region 枚举定义

        enum FieldName
        {
            //阀门
            ValveMethanol,
            ValveFan,
            ValveMethanolBottom,
            ValveMethanolTop,
            ValveInSteam,
            ValveSteamSplitter,
            ValveSteamDrum,
            ValveInSoftwater,
            ValveSteamSupheater,
            ValveSupheaterLeft,
            ValveSupheaterRight,
            ValveFirefilter,
            ValveMixOxidation,
            ValveInEvaporator,
            ValveOutOxidation,
            ValveCold,
            ValveInSplitter,
            ValveOutSteam,




            //管道
            FlowAir,
            FlowInMethanol,
            FlowMethanol,
            FlowInSteam,
            FlowSplitter,
            FlowInSoftwater,
            FlowSteamSupheater,
            FlowInSplitter,
            FlowOutOxidation,
            FlowMethanolEvap,
            FlowMixSupheater,
            FlowMixOxidation,
            FlowSupheater,
            FlowFirefilter,
            FlowColdDown,
            FlowColdUp,
            FlowOutSteam,
            FlowMethanolBack,



            //标签
            LabelLevelMethanol,
            LabelFlowMethanol,
            LabelFlowAir,
            LabelTempEvaporator,
            LabelTempOxidation,
            LabelGasMethanolRate,
            LabelSplitterPressure,
            LabelWaterMethanolRate,
            LabelEvaporatorPressure,
            LabelTempSupheater,
            LabelDrumPressure,
            LabelLevelEvap,
            LabelConcentration,

            //闪烁
            FlashLevelMethanol,
            FlashFlowMethanol,
            FlashFlowAir,
            FlashTempEvaporator,
            FlashTemoOxidation,
        }

        enum StatusName
        {
            甲醇进料阀, 风机阀, 甲醇流量计下阀, 甲醇流量计上阀, 外部蒸汽阀, 蒸汽进蒸汽分配器阀, 蒸汽进汽包阀, 软水进阀, 蒸汽进过热器及阻火过滤器阀, 氧化器蒸汽进蒸汽分配器阀门,
            甲醇进甲醇蒸发器阀, 过热器左侧阀, 过热器右侧阀, 阻火过滤器阀, 混合气体进氧化器阀, 蒸汽用气处阀, 甲醇液位, 甲醇流量, 空气流量, 甲醇蒸发器温度, 氧化器温度, 氧醇比, 蒸汽分配器压力,
            汽包蒸汽流入蒸汽分配器阀, 水醇比, 甲醇蒸发器压力, 过热器温度, 汽包压力, 蒸发器液位, 甲醇平衡浓度, 循环水进氧化器阀,
        }

        class Step
        {
            public Dictionary<StatusName, double> status = new Dictionary<StatusName, double>();
            public DateTime Date { get; set; }
        }
        #endregion
    }
}
